package leetbook.hash;

import java.util.HashMap;

public class Solution454 {

    public int fourSumCount1(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
        int len1 = nums1.length, len2 = nums2.length;
        int len3 = nums3.length, len4 = nums4.length;
        int count = 0;
        for (int i = 0; i < len1; i++) {
            for (int j = 0; j < len2; j++) {
                for (int k = 0; k < len3; k++) {
                    for (int l = 0; l < len4; l++) {
                        if(nums1[i]+nums2[j]+nums3[k]+nums4[l]==0){
                            count++;
                        }
                    }
                }
            }
        }
        return count;
    }

    /**
     * 空间换时间
     * 把nums1和num2和的所有组合存到一个hashmap里，key是和，value是次数
     */
    public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
        int count = 0;
        HashMap<Integer,Integer> hashMap = new HashMap<>();
        for (int i = 0; i < nums1.length; i++) {
            for (int j = 0; j < nums2.length; j++) {
                int tmp = nums1[i]+nums2[j];
                hashMap.put(tmp,hashMap.getOrDefault(tmp,0)+1);
            }
        }
        for (int i = 0; i < nums3.length; i++) {
            for (int j = 0; j < nums4.length; j++) {
                int tmp = nums3[i]+nums4[j];
                count += hashMap.getOrDefault(-tmp,0);
            }
        }
        return count;
    }

}
